<?php
namespace admin\model;
use framework\core\Model;
class CategoryModel extends Model{
    protected $login_table="ask_category";
    public function category_add($data){
        if ($data['cat_name']==''){
            $this->error[]='标题不能为空';
        }else if ((int)$data['cat_name']!=0){
            $this->error[]='标题不能是纯数字';
        }else if ($this->isExistCategory($data['cat_name'],$data['parent_id'])){
            $this->error[]='一个分类下面不能有相同的子类添加';
        }
        if (!empty($this->error)){
            return false;
        }
        return $this->insert($data);
    }
    public function isExistCategory($cat_name,$parent_id){
//        判断存在不存在 不要字段 建议写成1
        $sql="select 1 from $this->true_table where cat_name='$cat_name' and parent_id=$parent_id";
        return $this->dao->fetchOne($sql);
    }
    public function category_select(){
        $data=array('cat_name','parent_id');
        $cat_list=$this->select($data);
        return $this->getChildCategory($cat_list);
    }
    public function getChildCategory($cat_list,$p_id=0,$level=0){
        static $arr=array();
        foreach ($cat_list as $k=>$v){
            if ($v['parent_id']==$p_id){
                $v['level']=$level;
                $arr[]=$v;
                $this->getChildCategory($cat_list,$v['cat_id'],$level+1);
            }
        }
        return $arr;
    }
    //定义一个查询是否有子类的方法
    public function isLeafCategory($cat_id){
        $sql="select 1 from $this->true_table where parent_id=$cat_id";
        return $this->dao->fetchOne($sql);
    }
    //根据cat_id查询对应的图片地址
    public function getCatlogoById($cat_id){
        $sql="select cat_logo from $this->true_table where cat_id=$cat_id";
        return $this->dao->fetchOne($sql);
    }
    //定义一个删除分类的方法
    public function deleteCategory($cat_id)
    {
        return $this->delete($cat_id);
    }
    public function category_update($data){
        if ($data['cat_name']==''){
            $this->error[]='标题不能为空';
        }else if((int)$data['cat_name']!=0){
            $this->error[]='标题不能是纯数字';
        }
        if(!empty($this->error)){
            return false;
        }
        return $this->update($data,array('cat_id'=>$data['cat_id']));
    }
    public function getInfoById($cat_id){
        $sql="select * from $this->true_table where cat_id=$cat_id";
        return $this->dao->fetchRow($sql);
    }
}